package com.zxgllhh.db;

import java.sql.Connection;
import java.sql.Driver;
import java.util.Properties;

/**
 * 
 * @author Zhao,XingGuo
 *
 */
public class ConnectionFactory {

	private static ClassLoader externalClassLoader;

	private static ConnectionFactory instance = new ConnectionFactory();

	public static ConnectionFactory getInstance() {
		return instance;
	}

	private ConnectionFactory() {
		super();
	}

	public Connection getConnection(JDBCConnectionConfiguration config) throws Exception {

		Driver driver = ConnectionFactory.getDriver(config);
		Properties props = new Properties();
		props.setProperty("user", config.getUserId());
		props.setProperty("password", config.getPassword());
		Connection conn = driver.connect(config.getConnectionURL(), props);
		return conn;
	}

	public static Driver getDriver(JDBCConnectionConfiguration connectionInformation) throws Exception {
		String driverClass = connectionInformation.getDriverClass();
		Driver driver;
		Class<?> clazz = ConnectionFactory.externalClassForName(driverClass);
		driver = (Driver) clazz.newInstance();
		return driver;
	}

	public static Class<?> externalClassForName(String type) throws ClassNotFoundException {
		Class<?> clazz;
		try {
			clazz = getClassLoader().loadClass(type);
		} catch (Throwable e) {
			// ignore - fail safe below
			clazz = null;
		}
		if (clazz == null) {
			clazz = Class.forName(type);
		}

		return clazz;
	}

	private static ClassLoader getClassLoader() {
		if (externalClassLoader != null) {
			return externalClassLoader;
		} else {
			return Thread.currentThread().getContextClassLoader();
		}
	}
}
